package com.iotest.path;

import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.UserPrincipal;

/**
 * @Author: huhx
 * @Date: 2017-11-10 下午 4:24
 */
public class PathTest {

    @Test
    public void pathTest_1() {
        Path path = Paths.get("huhx-test/file/huhx.txt");
        System.out.println(path.getFileName()); // huhx.txt
        System.out.println(path.getParent()); // huhx-test\file
        System.out.println(path.toString()); // huhx-test\file\huhx.txt
        System.out.println(path.toAbsolutePath().toString()); // G:\Java\JavaEE\Program\2016-05-15\SpringLearn\huhx-test\huhx-test\file\huhx.txt

        Path path1 = Paths.get("huhx-test/file/linux.txt");
        System.out.println(path.relativize(path1)); // ..\linux.txt
    }

    @Test
    public void filesTest_1() throws IOException {
        Path inputPath = Paths.get("file/huhx.txt");
        Path outputPath = Paths.get("file/huhxOutput.txt");
        UserPrincipal owner = Files.getOwner(Paths.get("file/huhx.txt"));
        System.out.println(owner.getName());

        Files.copy(inputPath, outputPath);
    }

    @Test
    public void moveFile() throws IOException {
        Path inputPath = Paths.get("file/huhx.txt");
        Path path = Files.move(inputPath, Paths.get("file/huhxMove.txt"));
        System.out.println(path.toAbsolutePath().toString());
    }

    @Test
    public void fileAttribute() throws IOException {
        Path path = Paths.get("file/huhxMove.txt");
        System.out.println("is directory: " + Files.isDirectory(path)); // false
        System.out.println("size: " + Files.size(path)); // 169

        // 属性的类
        BasicFileAttributes basicFileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.println("is regular file: " + basicFileAttributes.isRegularFile());
        System.out.println("size: " + basicFileAttributes.size());
        System.out.println("time: " + basicFileAttributes.lastModifiedTime());

        FileTime fileTime = FileTime.fromMillis(System.currentTimeMillis());
//        Files.setLastModifiedTime(path, fileTime);
        Files.setAttribute(path, "lastModifiedTime", fileTime);

        // dos
        DosFileAttributes dosFileAttributes = Files.readAttributes(path, DosFileAttributes.class);
        System.out.println("is readOnly: " + dosFileAttributes.isReadOnly());
    }
}
